#pragma once
#include <string>
#include <memory>
#include <functional>

#include "SocketIO.h"
#include "InetAddress.h"
#include "Socket.h"


class EventLoop;


class TcpConnection:public std::enable_shared_from_this<TcpConnection>{
    using TcpConnectionPtr = std::shared_ptr<TcpConnection>;
    using TcpConnectionCallback = std::function<void(const TcpConnectionPtr&)>;
private:
    SocketIO _socketIO;
    //为了调试用
    Socket _sock;
    InetAddress _peerAddr;
    InetAddress _localAddr;

    TcpConnectionCallback _onNewConnectionCb;//连接建立
    TcpConnectionCallback _onMessageCb;//消息到达
    TcpConnectionCallback _onCloseCb;//连接关闭

    EventLoop * _loop;//事件循环


public:
    explicit TcpConnection(int fd,EventLoop* loop);
    ~TcpConnection();
    void send(const std::string & msg );
    std::string receive();
    std::string toString();
    bool isClosed() const;


    void setOnNewConnection(const TcpConnectionCallback& cb);
    void setMessageCallback(const TcpConnectionCallback& cb);
    void setCloseCallback(const TcpConnectionCallback& cb);

    //三个回调的执行函数
    void handleNewConnectionCallback();
    void handleMessageCallback();
    void handleCloseCallback();
    //此处的msg参数是处理好的业务数据，有线程池中线程执行
    void sendInLoop(const std::string & msg);
private:
    InetAddress getPeerAddr();
    InetAddress getLocalAddr();
};